package lp.polimi.treefinder;


import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;

/**
 * Default tab listener for displaying a fragment when a tab is selected and
 * hide it when the tab is unselected.
 */
public class TabListener<T extends Fragment> implements ActionBar.TabListener {

	private Fragment mFragment;
	private final Activity mActivity;
	private final String mTag;
	private final Class<T> mClass;

	/** Constructor used each time a new tab is created.
	 * @param activity  The host Activity, used to instantiate the fragment
	 * @param tag  The identifier tag for the fragment
	 * @param clz  The fragment's Class, used to instantiate the fragment
	 */
	public TabListener(Activity activity, String tag, Class<T> clz) {
		mActivity = activity;
		mTag = tag;
		mClass = clz;
		mFragment=mActivity.getFragmentManager().findFragmentByTag(mTag);
	}


	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		
		ft.setCustomAnimations(
                R.animator.card_flip_right_in, R.animator.card_flip_right_out);
		
		// Check if the fragment is already initialized
		if (mFragment == null) {
			// If not, instantiate and add it to the activity
			mFragment = Fragment.instantiate(mActivity, mClass.getName());
			ft.add(android.R.id.content, mFragment, mTag);
		} else {
			// If it exists, simply attach it in order to show it
			ft.attach(mFragment);

		}
	}


	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		
		ft.setCustomAnimations(
                R.animator.card_flip_right_in, R.animator.card_flip_right_out);
		
		if (mFragment != null) {
			// Detach the fragment, because another one is being attached
			//ft.hide(mFragment);
			ft.detach(mFragment);
		}
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// User selected the already selected tab. Usually do nothing.
	}
}